<?php

namespace addons\exam\controller;

use addons\exam\enum\CateUses;
use addons\exam\enum\CommonStatus;
use addons\exam\model\CateUserLogModel;
use addons\exam\model\QuestionModel;
use addons\exam\model\UserModel;
use app\admin\model\exam\CateModel;
use app\admin\model\exam\QuestionCollectModel;
use app\admin\model\exam\QuestionWrongModel;


/**
 * 试题接口
 */
class Question extends Base
{
    protected $noNeedLogin = '';
    protected $noNeedRight = ['*'];

    /**
     * 看题模式
     */
    public function lookPage()
    {
        $model = new QuestionModel();
        $total = $model->where('cate_id', $this->request->param('cate_id'))->count('id');
        $this->success('', compact('total'));
    }

    /**
     * 练习模式
     */
    public function train()
    {
        $param            = $this->request->param();
        $param['user_id'] = $this->auth->id;

        // 验证是否需要绑定手机号
        UserModel::isMustBindMobile($this->auth->getUser());

        if (!input('just_get_count/d', 0)) {
            if (($cate_id = input('cate_id/d')) && ($cate = CateModel::get($cate_id))) {
                if ($cate['uses'] == CateUses::ONLY_MEMBER && !UserModel::isMember($this->auth->id)) {
                    $this->error('该题目类型仅针对会员开放，请开通会员后再试');
                }
                if (!$cate['is_free'] && $cate['price'] > 0) {
                    if (!CateUserLogModel::isOpenCate($this->auth->id, $cate_id)) {
                        $this->error('该题库需要付费开通，请先购买后再试', ['need_open' => true, 'cate' => $cate]);
                    }
                }
            }
        }

        $list = QuestionModel::getList($param);
        $this->success('', $list);
    }

    /**
     * 根据关键词模糊查询10条题目
     */
    public function search()
    {
        $cahce_key = 'search:'.$this->auth->id;
        $this->checkRepeatKey($cahce_key);

        $query = \addons\exam\model\QuestionModel::with(
            [
                'cates' => function ($query) {
                    $query->field('id,name');
                },
            ]
        )->where('status', CommonStatus::NORMAL);

        if ($keyword = input('keyword/s', '', 'trim,strip_tags,htmlspecialchars,xss_clean')) {
            if (mb_strlen($keyword) < 2) {
                $this->error('请输入不少于2个字的关键词进行搜索');
            }

            $query->where('title', 'like', '%' . $keyword . '%');
        }

        if ($sort_type = input('sort_type/s')) {
            $query->order($sort_type);
        }

        if (input('sort_rand/d', 0)) {
            $query->orderRaw('rand()');
        }

        //   试题分类
        if ($kind = input('kind/s', '')) {
            $query->where('kind',$kind);
        }

        switch ($kind) {
            case 'WORD':
                $query->where('is_read',0);
                break;
            
            default:
                # code...
                break;
        }


        $list = $query->paginate(15, true)->toArray();
        // // 最多搜索5页
        // if (input('page/d') >= 5) {
        //     $list['has_more'] = false;
        // }

        $this->success('', ['list' => $list]);
    }

    /**
     * 试题详情
     */
    public function detail($id)
    {
        $this->success('', (new QuestionModel)->get($id));
    }

    /**
     * 试题详情
     */
    public function info()
    {
        $id = input('id/d', 0);
        if(empty($id)){
            return  $this->error('参数错误');
        }

        $info = (new QuestionModel)->get($id)->toArray();

        if($info['kind'] == 'FILL'){

            $fill  = explode('______',$info['title']);
            $title = [];
            foreach($fill as $value){
                if(empty($value)){
                    continue;
                }
                $title = array_merge($title,[['type' => 1, 'value' => $value,'width'=>''],['type' => 0, 'value' => '','width'=>'']]);
            }
            $info['fill_title'] = $title;
        }elseif($info['kind'] == 'WORD'){
   
            $xf_th_text = '';
            if(!empty($info['xf_content'])){
   
                if($info['is_word'] == 0){
                    $xf_th_text .= '[word]';
                }else{
                    $xf_th_text .= '[content]';
                }

                $xf_th_text .= $info['xf_content'];

                if(!empty($info['vocabulary'])){
                    $xf_th_text .= '[vocabulary]'.$info['vocabulary'];
                }

                if(!empty($info['number_replace'])){
                    $xf_th_text .= '[number_replace]'.$info['number_replace'];
                }
            }
            
            $info['xf_text'] = $xf_th_text;
        }
        $this->success('', $info);
    }

    /**
     * 收藏列表
     */
    public function collectList()
    {   
        $user_id         = $this->auth->id;
        $page_info       = $this->getPerPage();
        $collectQuestion = new QuestionCollectModel();
        $type = input('type/d',1);

        if ($keyword = input('keyword/s', '', 'trim,strip_tags,htmlspecialchars,xss_clean')) {
            if (mb_strlen($keyword) < 2) {
                $this->error('请输入不少于2个字的关键词进行搜索');
            }
            
            $list   = $collectQuestion::with('question')->where('question.title', 'like', '%' . $keyword . '%')->where('user_id', $user_id)->where('type',$type)->order('id desc')->paginate($page_info['num'])->toArray();
            $total  = $collectQuestion::where('title', 'like', '%' . $keyword . '%')->where('user_id', $user_id)->where('type',$type)->count();
        }else{
            $list   = $collectQuestion::with('question')->where('user_id', $user_id)->where('type',$type)->order('id desc')->paginate($page_info['num'])->toArray();
            $total  = $collectQuestion::where('user_id', $user_id)->where('type',$type)->count();
        }
        if(!empty($list['data'])){
            foreach($list['data'] as &$value){
                if($value['kind'] == 'WORD'){
                
                    $xf_th_text = '';
                    if(!empty($value['question']['xf_content'])){
           
                        if($value['question']['is_word'] == 0){
                            $xf_th_text .= '[word]';
                        }else{
                            $xf_th_text .= '[content]';
                        }
        
                        $xf_th_text .= $value['question']['xf_content'];
        
                        if(!empty($value['question']['vocabulary'])){
                            $xf_th_text .= '[vocabulary]'.$value['question']['vocabulary'];
                        }
        
                        if(!empty($value['question']['number_replace'])){
                            $xf_th_text .= '[number_replace]'.$value['question']['number_replace'];
                        }
                    }
                 
                    $value['question']['xf_text'] = $xf_th_text ?? '';
                }
            }
        }
        $this->success('', compact('list', 'total'));
    }

    /**
     * 添加收藏
     */
    public function collectAdd()
    {
        $cache_key = 'collectAdd:'.$this->auth->id;
        $this->checkRepeatKey($cache_key);

        if (!$question_id = input('question_id/d', 0)) {
            $this->error('缺少题目ID');
        }

        $question = QuestionModel::where('id', $question_id)->field('id,title,kind,is_word')->find();
        if (!$question) {
            $this->error('题目数据不存在');
        }
        $type = 1;
        if($question['is_word'] == 1){
            $type = 2;
        }
        // 1:单词、2句子
        if ($res = QuestionCollectModel::updateOrCreate(
            [
                'user_id'     => $this->auth->id,
                'question_id' => $question_id,
                'title'       => $question['title'],
                'kind'        => $question['kind'],
                'type'        => $type
            ],
            [
                'user_id'     => $this->auth->id,
                'question_id' => $question_id,
                'title'       => $question['title'],
                'kind'        => $question['kind'],
                'type'        => $type
            ])
        ) {
            $this->success('收藏成功', $res);
        }
        $this->error('收藏失败');
    }

    /**
     * 取消收藏
     */
    public function collectCancel()
    {

        $cache_key = 'collectCancel:'.$this->auth->id;
        $this->checkRepeatKey($cache_key);

        if (!$question_id = input('question_id/d', 0)) {
            $this->error('缺少题目ID');
        }
        $result = QuestionCollectModel::where('question_id', $question_id)->where('user_id', $this->auth->id)->delete();

        if ($result) {
            $this->success('取消成功');
        }
        $this->error('取消失败');
    }

    /**
     * 获取错题列表
     */
    public function wrongList()
    {
        $user_id = $this->auth->id;

        if ($ids = input('question_ids')) {
            $total = QuestionWrongModel::where('user_id', $user_id)->whereIn('question_id', $ids)->count();
            $list  = $total ? QuestionWrongModel::with('question')
                ->whereIn('question_id', $ids)
                ->where('user_id', $user_id)
                ->order('id desc')
                ->paginate(999, true)->toArray() : [];
        } else {
            $total = QuestionWrongModel::where('user_id', $user_id)->count();
            $list  = $total ? QuestionWrongModel::with('question')
                ->where('user_id', $user_id)
                ->order('id desc')
                ->paginate(999, true)->toArray() : [];
        }

        if (isset($list['data']) && $list['data']) {
            $questions = [];
            foreach ($list['data'] as $item) {
                $questions[] = array_merge($item['question'], ['wrong_id' => $item['id'], 'user_answer' => $item['user_answer']]);
            }
            $list['data'] = \addons\exam\model\QuestionModel::isCollected($user_id, $questions);
        } else {
            $list['data'] = [];
        }

        $this->success('', compact('list', 'total'));
    }

    /*
     * 记录错题
     */
    public function wrongAdd()
    {
        if (!$question_id = input('question_id/d', 0)) {
            $this->error('缺少题目ID');
        }

        if (QuestionWrongModel::add($this->auth->id, $question_id))
            $this->success('记录成功');
        else
            $this->error('记录失败');
    }

    /**
     * 删除错题
     */
    public function wrongDelete()
    {
        if (!$question_id = input('question_id/d', 0)) {
            $this->success('缺少错题ID');
        }

        if (QuestionWrongModel::where('question_id', $question_id)->where('user_id', $this->auth->id)->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**
     * 清空所有错题
     */
    public function wrongClear()
    {
        if (QuestionWrongModel::where('user_id', $this->auth->id)->delete()) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
}
